package com.zhuozhengsoft.springbootpageoffice.controller;

import com.zhuozhengsoft.pageoffice.*;
import com.zhuozhengsoft.springbootpageoffice.util.GetDirPathUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(value = "/FileMakerConvertPDFs")
public class FileMakerConvertPDFsController {

    //获取doc目录的磁盘路径
    private String dir = GetDirPathUtil.getDirPath() + "static/doc/";

    @RequestMapping(value = "/Default")
    public ModelAndView index(HttpServletRequest request) {

        ModelAndView mv = new ModelAndView("FileMakerConvertPDFs/Default");
        return mv;
    }

    @RequestMapping(value = "/Edit")
    public ModelAndView editWord(HttpServletRequest request, Map<String, Object> map) {
        String id = request.getParameter("id").trim();
        String docName = "doc0" + id + ".doc";
        PageOfficeCtrl poCtrl1 = new PageOfficeCtrl(request);

        poCtrl1.webOpen("/doc/FileMakerConvertPDFs/" + docName, OpenModeType.docNormalEdit, "张三");
        map.put("pageoffice", poCtrl1.getHtml());
        ModelAndView mv = new ModelAndView("FileMakerConvertPDFs/Edit");
        return mv;
    }

    @RequestMapping(value = "/Convert")
    public void showWord(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String id = request.getParameter("id").trim();
        String docName = "doc0" + id + ".doc";
        String pdfName = "doc0" + id + ".pdf";

        FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
        fmCtrl.fillDocumentAsPDF("/doc/FileMakerConvertPDFs/" + docName, DocumentOpenType.Word, pdfName);
        response.getOutputStream().print(fmCtrl.getHtml());
    }

    @RequestMapping(value = "/save")
    public void save(HttpServletRequest request,HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        fs.saveToFile(dir + "FileMakerConvertPDFs/"+ fs.getFileName());
        //设置自定义保存结果，用来返回给前端页面，setCustomSaveResult的参数也可以是json字符串类型
        //设置文件的保存结果
        fs.setCustomSaveResult("ok");
        fs.close();
    }
}
